package com.hyper_yang._05_juc.chap02;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 演示
 *  ReentrantLock：提供的
 *  lock()方法，获取不到锁，死等。不见不散。容易出现死锁。
 *  tryLock()方法可以避免死锁。- 限时等待。过时不够。
 */
public class DeadlockDemo2 {

    private static ReentrantLock lock1 = new ReentrantLock();
    private static ReentrantLock lock2 = new ReentrantLock();


    public static void main(String[] args) {
        new Thread(()->{
            boolean flag1 = lock1.tryLock(); //尝试获取锁，获取了就干活，否则走人。
            //boolean flag1 = lock1.tryLock(1, TimeUnit.SECONDS); //尝试获取锁，获取不到时需要等待指定的时间，如果时间过后还拿不到锁，才会走人。
            if(flag1){
                try {
                    System.out.println("A 获取了 lock1 ");
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("A 准备获取 lock2 ");
                    boolean flag2 = lock2.tryLock();
                    if(flag2){
                        try {
                            System.out.println("A 获取了 lock2 ");
                        } finally {
                            lock2.unlock();
                            System.out.println("A 释放了 lock2 ");
                        }
                    }else{
                        System.out.println("A 未获取了 lock2 ");
                    }
                } finally {
                    lock1.unlock();
                    System.out.println("A 释放了 lock1 ");
                }
            }else{
                System.out.println("A 未获取了 lock1 ");
            }
        },"A").start();

        new Thread(()->{
            boolean flag2 = lock2.tryLock();
            if(flag2){
                try {
                    System.out.println("B 获取了 lock2 ");
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("B 准备获取 lock1 ");
                    boolean flag1 = lock1.tryLock();
                    if(flag1){
                        try {
                            System.out.println("B 获取了 lock1 ");
                        } finally {
                            lock1.unlock();
                            System.out.println("B 释放了 lock1 ");
                        }
                    }else{
                        System.out.println("B 未获取了 lock1 ");
                    }
                } finally {
                    lock2.unlock();
                    System.out.println("B 释放了 lock2 ");
                }
            }else{
                System.out.println("B 未获取了 lock2 ");
            }
        },"B").start();
    }
}